package com.dzsw.dp.corp.chain.handler;

import java.util.Objects;


public abstract class GeneralHandler<GeneralHandlerRequest, GeneralHandlerResponse> {

    protected GeneralHandler nextHandler;
    protected GeneralHandler preHandler;

    public void setPre(GeneralHandler handler) {
        this.preHandler = handler;
    }

    public void setNext(GeneralHandler handler) {
        this.nextHandler = handler;
    }

    /**
     * 调用前一个handler
     *
     * @param request
     */
    private void pre(GeneralHandlerRequest request, GeneralHandlerResponse response) {
        // 反向执行
        this.afterCompletion(request, response);
        if (!Objects.isNull(preHandler)) {
            preHandler.pre(request, response);
        }
    }

    /**
     * 调用下一个handler
     *
     * @param request
     */
    private void next(GeneralHandlerRequest request, GeneralHandlerResponse response) {
        if (Objects.isNull(nextHandler)) {
            // 开始反向执行
            this.afterCompletion(request,response);
            if (!Objects.isNull(preHandler)) {
                preHandler.pre(request, response);
            }
        } else {
            // 正向执行handler
            nextHandler.handle(request, response);
            nextHandler.next(request, response);
        }
    }

    /**
     * 责任链正向处理
     *
     * @param request
     */
    protected abstract void handle(GeneralHandlerRequest request, GeneralHandlerResponse response);

    /**
     * 责任链反向处理
     *
     * @param request
     */
    protected abstract void afterCompletion(GeneralHandlerRequest request, GeneralHandlerResponse response);

    /**
     * 开始执行处理链
     *
     * @param request
     */
    public void startHandler(GeneralHandlerRequest request, GeneralHandlerResponse response) {
        this.handle(request, response);
        this.next(request, response);
    }

}
